package com.runen.infinitemovement.base;


import android.util.Log;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.UserEntity;
import com.runen.rxnetlibrary.net.HttpClientManager;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.EncryptUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author LiaoDuanHong
 * @date 2018/9/20
 */
public class BaseAPI {
    protected HttpClientManager httpClientManager;

    private UserEntity userInfo;

    //token:  eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI2MDQ5NTM1NDg1OTUyMCIsImlhdCI6MTUzOTI0NDc5NiwiZXhwIjoxNTM5ODQ5NTk2fQ.ty_clrCj8XuKoxT1lCwvO7fjaCP0OD3FxpoDiqelO0ZM6ADyHI1ZmMLWH8cSNMt38lGt4HyIaRa7_oNQ6Q830g
    public BaseAPI() {
        userInfo = UserAPI.getUserInfo();
        TreeMap<String, String> header = new TreeMap<String, String>();
        String token;
//        // 登陆后增加authorization
        if (userInfo != null) {
            if (userInfo.data != null) {
                token = "Bearer %s";
                header.put("Authorization", String.format(token, userInfo.data.access_token));
            }
        } else {
            token = "Basic %s";
            header.put("Authorization", String.format(token, EncryptUtils.encodeBase64("app:app")));
        }
        header.put("Content-Type", "application/json");
        httpClientManager = HttpClientManager.getInstance().setHeader(header);
    }
    


    private TreeMap<String, String> getSystemTreeMap(Map hashMap) {

        long time = System.currentTimeMillis();
        TreeMap<String, String> hashMapStr = new TreeMap<>();
        if (hashMap == null) {
            hashMap = new TreeMap<>();
        }
//        if (!StringUtil.isEmpty(UserAPI.getUserId())) {
//            hashMap.put("userId", UserAPI.getUserId());
//        }
//        hashMap.put("timestamp", String.valueOf(time));
        hashMapStr.putAll(hashMap);
//        hashMapStr.put("sign", sign(hashMapStr));
//        hashMapStr.put("appKey", Constant.APP_KEY);
        return hashMapStr;
    }


    /**
     * post 方式请求
     *
     * @param action   请求的方法名称
     * @param hashMap  请求业务参数,可以为null
     * @param listener
     */
    public void post(String action, Map<String, Object> hashMap,
                     BaseResultCallback<?> listener) {
        httpClientManager.post(String.format("%s%s", Constant.BASE_HOST, action), getSystemTreeMap(hashMap), listener);
    }

    /**
     * get方式请求
     *
     * @param action   请求的地址
     * @param hashMap  请求业务参数 可以为null
     * @param listener
     */
    public void get(String action, Map hashMap, BaseResultCallback<?> listener) {
        Log.e("httpclient", "get: " + action);
        httpClientManager.get(String.format("%s%s", Constant.BASE_HOST, action), getSystemTreeMap(hashMap), listener);
    }

    public void pathGet(String action, Map hashMap, BaseResultCallback<?> listener) {
        httpClientManager.get(String.format("%s", action), getSystemTreeMap(hashMap), listener);
    }

    /**
     * get方式请求
     *
     * @param action   请求的地址
     * @param jsonBody 请求业务参数 json
     * @param listener
     */
    public void getBody(String action, String jsonBody, BaseResultCallback<?> listener) {
        httpClientManager.getBody(String.format("%s%s", Constant.BASE_HOST, action), jsonBody, listener);
    }

    /**
     * post方式请求
     *
     * @param action   请求的地址
     * @param jsonBody 请求业务参数 json
     * @param listener
     */
    public void postBody(String action, String jsonBody, BaseResultCallback<?> listener) {
        httpClientManager.postBody(String.format("%s%s", Constant.BASE_HOST, action), jsonBody, listener);
    }

    /**
     * get方式请求
     *
     * @param action   请求的地址
     * @param hashMap  请求业务参数 可以为null
     * @param listener
     */
    public void delete(String action, TreeMap<String, String> hashMap, BaseResultCallback<?> listener) {
        httpClientManager.delete(String.format("%s%s", Constant.BASE_HOST, action), getSystemTreeMap(hashMap), listener);
    }

    public void deleteBody(String action, JSONObject jsonBody, BaseResultCallback<?> listener) {
        httpClientManager.delete(String.format("%s%s", Constant.BASE_HOST, action), jsonBody, listener);
    }

    /**
     * 带文件的post 多表单提交
     *
     * @param action   请求的地址
     * @param hashMap  请求参数 可以为null
     * @param files    文件参数 可以为null
     * @param listener
     */
    public void postFile(String action, TreeMap<String, String> hashMap, TreeMap<String, File> files, BaseResultCallback<?> listener) {
        httpClientManager.postFiles(String.format("%s%s", Constant.BASE_HOST, action), getSystemTreeMap(hashMap), files, listener);
    }

    public void postFiles(String action, TreeMap<String, List<File>> files, BaseResultCallback<?> listener) {
        httpClientManager.postFiles(String.format("%s%s", Constant.BASE_HOST, action), files, listener);
    }

    public void postFilesType(String action, TreeMap<String, String> hashMap, TreeMap<String, List<File>> files, BaseResultCallback<?> listener) {
        httpClientManager.postFilesType(String.format("%s%s", Constant.BASE_HOST, action), hashMap, files, listener);
    }

    /**
     * 遍历map构造get参数字符串，此方法时候传统的get key=value& 参数 ...
     *
     * @param map
     * @return 返回get 全路径
     */
    private String getUrlParmas(Map<String, Object> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }
        if (sb.length() == 0) {
            return "";
        } else {
            return sb.substring(0, sb.length() - 1);
        }
    }

    /**
     * 将数据集合转化拼成字符串
     *
     * @param collection 集合
     * @param delimiter  分隔符
     * @return
     */
    public static String join(Collection<?> collection, String delimiter) {
        StringBuilder builder = new StringBuilder();
        Iterator<?> iterator = collection.iterator();
        while (iterator.hasNext()) {
            builder.append(iterator.next());
            if (iterator.hasNext()) {
                builder.append(delimiter);
            }
        }
        return builder.toString();
    }

}
